package map.android.baidu.carpool.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;

public class SmsUtils {
	private static final String INFO_KEYWORD = "【百度】";
	private static final Uri mSmsUri = Uri.parse("content://sms/");
	private static final Uri mInboxUri = Uri.parse("content://sms/inbox");
	
	private SmsContent mSmsContent;
	private Activity mActivity;
	private OnVerCodeCallBack mListener;

	public SmsUtils(Activity activity) {
		this.mActivity = activity;
		this.mSmsContent = new SmsContent(new Handler());
	}

	public static String getDynamicPassword(String body,int length) {
		if (TextUtils.isEmpty(body) || !body.contains(INFO_KEYWORD))
			return null;
		
//		Matcher localMatcher = Pattern.compile("[0-9\\.]+").matcher(body);
//		while (localMatcher.find()){
//			if(localMatcher.group().length() == 6){
//				return localMatcher.group();
//			}
//		};
//		return null;
		
		// 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字
        // (?<!--[a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字
        // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现
        Pattern p = Pattern.compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + length + "})(?![a-zA-Z0-9])");
        Matcher m = p.matcher(body);
        if (m.find()) {
            return m.group(0);
        }
        return null;
	}

	public void registerSMS() {
		this.mActivity.getContentResolver().registerContentObserver(mSmsUri, true, this.mSmsContent);
	}
	public void unRegisterSMS() {
		this.mActivity.getContentResolver().unregisterContentObserver(this.mSmsContent);
	}
	
	public void setOnVerCodeListener(OnVerCodeCallBack listener) {
		this.mListener = listener;
	}

	public static abstract interface OnVerCodeCallBack {
		public abstract void onVerCodeSetText(String str);
	}

	public final class SmsContent extends ContentObserver {
		private Cursor cursor = null;

		public SmsContent(Handler handler) {
			super(handler);
		}

		public void onChange(boolean flags) {
			super.onChange(flags);
			String[] arrayOfString = new String[4];
			arrayOfString[0] = "_id";
			arrayOfString[1] = "address";
			arrayOfString[2] = "read";
			arrayOfString[3] = "body";
			this.cursor = mActivity.managedQuery(mInboxUri, arrayOfString, null, null, "date desc");
			if ((this.cursor == null) || (this.cursor.getCount() <= 0))
				return;
			this.cursor.moveToNext();
			int i = this.cursor.getColumnIndex("body");
			String str = getDynamicPassword(this.cursor.getString(i),6);
			if (TextUtils.isEmpty(str))
				return;
			mListener.onVerCodeSetText(str);
		}
	}
}